package com.aloda.controller.user;

import cn.hutool.core.bean.BeanUtil;
import com.aloda.annotation.LoginLogAnno;
import com.aloda.constant.ErrorCode;
import com.aloda.constant.UserConstant;
import com.aloda.context.UserBaseContext;
import com.aloda.dto.user.UserEditDTO;
import com.aloda.dto.user.UserLoginDTO;
import com.aloda.dto.user.UserRegisterByEmailDTO;
import com.aloda.dto.user.UserRegisterDTO;
import com.aloda.exception.WarnException;
import com.aloda.query.SearchPageDTO;
import com.aloda.query.UserCardPageQuery;
import com.aloda.result.Result;
import com.aloda.service.FollowService;
import com.aloda.service.UserService;
import com.aloda.utils.EncryptionUtil;
import com.aloda.vo.user.*;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;

/**
 * UserController
 *
 * @author aloda
 * @date 2024/12/19
 */
@Slf4j
@RequestMapping("/user/user")
@RestController("user")
public class UserController {

    @Resource
    private UserService userService;

    @Resource
    private FollowService followService;

    /**
     * 通过手机号进行注册
     *
     * @param userRegisterDTO
     * @return
     * @throws Exception
     */
    @PostMapping("/register")
    public Result registerByPhone(@RequestBody UserRegisterDTO userRegisterDTO) throws Exception {
        if (BeanUtil.isEmpty(userRegisterDTO)) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        log.info("用户注册：{}", userRegisterDTO);
        String decrypt = EncryptionUtil.decrypt(userRegisterDTO.getUserPassword());
        userRegisterDTO.setUserPassword(decrypt);
        userService.registerByPhone(userRegisterDTO);
        return Result.success("注册成功");
    }

    /**
     * 用户通过邮箱注册
     * @param userRegisterByEmailDTO
     * @return
     */
    @PostMapping("/register/email")
    public Result registerByEmail(@RequestBody UserRegisterByEmailDTO userRegisterByEmailDTO) throws Exception {
        if (BeanUtil.isEmpty(userRegisterByEmailDTO)) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        log.info("用户注册：{}", userRegisterByEmailDTO);
        String decrypt = EncryptionUtil.decrypt(userRegisterByEmailDTO.getUserPassword());
        userRegisterByEmailDTO.setUserPassword(decrypt);
        boolean re = userService.registerByEmail(userRegisterByEmailDTO);
        if (re) {
            return Result.success("注册成功");
        } else  {
            return Result.error("注册失败");
        }
    }


    /**
     * 通过账号登录
     *
     * @param userLoginDTO
     * @return
     * @throws Exception
     */
    @LoginLogAnno(desc = "用户登录")
    @PostMapping("/login")
    public Result<UserLoginVO> loginByAccount(@RequestBody UserLoginDTO userLoginDTO) throws Exception {
        if (BeanUtil.isEmpty(userLoginDTO)) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        log.info("用户登录：{}", userLoginDTO);
        String decrypt = EncryptionUtil.decrypt(userLoginDTO.getUserPassword());
        userLoginDTO.setUserPassword(decrypt);
        UserLoginVO userLoginVO = userService.loginByAccount(userLoginDTO);
        return Result.success(userLoginVO);
    }

    /**
     * 用户退出
     *
     * @return
     */
    @PostMapping("/logout")
    public Result userLogout(HttpServletRequest request) {
        log.info("用户退出：{}", UserBaseContext.getUser());
        userService.userLogout(request);
        return Result.success();
    }

    /**
     * 通过token获取用户信息
     *
     * @return
     */
    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfoByToken() {
        UserInfoVO userInfoVO = userService.getUserInfoByToken();
        return Result.success(userInfoVO);
    }

    /**
     * 用户编辑个人信息
     *
     * @param userEditDTO
     * @return
     */
    @PutMapping
    public Result editUserInfo(@RequestBody UserEditDTO userEditDTO) {
        if (BeanUtil.isEmpty(userEditDTO)) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        userService.editUserInfo(userEditDTO);
        return Result.success();
    }

    /**
     * 客户端根据关键词搜索
     *
     * @param searchPageDTO
     * @return
     */
    @PostMapping("/search")
    public Result<List<UserCardVO>> searchUser(@RequestBody SearchPageDTO searchPageDTO) {
        if (BeanUtil.isEmpty(searchPageDTO)) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        if (searchPageDTO.getCurrentPage() > UserConstant.MAX_CURRENT_PAGE) {
            return Result.success(Collections.emptyList());
        }
        return Result.success(userService.searchUser(searchPageDTO));
    }

    /**
     * 通过id获取脱敏用户信息
     *
     * @param id 用户id
     * @return 脱敏用户信息 UserCardVO
     */
    @GetMapping("/{id}")
    public Result<UserHomePageVO> getUserInfoById(@PathVariable Long id) {
        if (id == null) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        return Result.success(userService.getUserInfoById(id));
    }

    /**
     * 关注用户
     *
     * @param id
     * @return
     */
    @PostMapping("/follow/{id}")
    public Result<Boolean> followeeUser(@PathVariable Long id) {
        if (id == null) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        return Result.success(followService.followeeUser(id));
    }

    /**
     * 取消关注用户
     *
     * @param id
     * @return
     */
    @PostMapping("/unfollow/{id}")
    public Result<Boolean> cancelFollowUser(@PathVariable Long id) {
        if (id == null) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        return Result.success(followService.cancelFollowUser(id));
    }

    /**
     * 滚动分页查询id对应用户的粉丝用户卡片
     *
     * @param userCardPageQuery
     * @return
     */
    @PostMapping("/fans/page")
    public Result<List<UserCardVO>> getFansPage(@RequestBody UserCardPageQuery userCardPageQuery) {
        if (BeanUtil.isEmpty(userCardPageQuery)) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        if (userCardPageQuery.getCurrentPage() > UserConstant.MAX_CURRENT_PAGE) {
            return Result.success(Collections.emptyList());
        }
        return Result.success(userService.getFansPage(userCardPageQuery));
    }

    /**
     * 滚动分页查询id对应用户的关注用户卡片
     *
     * @param userCardPageQuery
     * @return
     */
    @PostMapping("/follows/page")
    public Result<List<UserCardVO>> getFollowsPage(@RequestBody UserCardPageQuery userCardPageQuery) {
        if (BeanUtil.isEmpty(userCardPageQuery)) {
            throw new WarnException(ErrorCode.PARAMS_ERROR);
        }
        if (userCardPageQuery.getCurrentPage() > UserConstant.MAX_CURRENT_PAGE) {
            return Result.success(Collections.emptyList());
        }
        return Result.success(userService.getFollowsPage(userCardPageQuery));
    }

    /**
     * 客户端设置应用访问权限
     * @return
     */
    @PutMapping("/app")
    public Result<Boolean> setAppAuth() {
        return Result.success(userService.setAppAuth());
    }

    /**
     * 客户端设置收藏访问权限
     * @return
     */
    @PutMapping("/collect")
    public Result<Boolean> setCollectAuth() {
        return Result.success(userService.setCollectAuth());
    }

    /**
     * 客户端修改密码
     * @param userRePwDTO
     * @return
     */
    @PutMapping("/pw")
    public Result<Boolean> resetUserPassword(@RequestBody UserRePwDTO userRePwDTO) {
        if (BeanUtil.isEmpty(userRePwDTO)) {
            return Result.error(ErrorCode.PARAMS_ERROR);
        }
        try {
            String decryptOldPw = EncryptionUtil.decrypt(userRePwDTO.getOldPassword());
            String decryptNewPw = EncryptionUtil.decrypt(userRePwDTO.getNewPassword());
            userRePwDTO.setOldPassword(decryptOldPw);
            userRePwDTO.setNewPassword(decryptNewPw);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        boolean b = userService.resetUserPassword(userRePwDTO);
        return Result.success(b);
    }
}
